package com.jesper.config;

import com.jesper.security.MyAuthenctiationFailureHandler;
import com.jesper.security.MyAuthenctiationSuccessHandler;
import com.jesper.service.MyUserDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@AllArgsConstructor
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    private final MyAuthenctiationSuccessHandler successHandler;
    private final MyAuthenctiationFailureHandler failureHandler;

    private final MyUserDetailsService myUserDetailsService;//安全框架下的用户信息构造对象


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
//                .and()
//                .inMemoryAuthentication()
//                .withUser("jesper")
//                .password("jesper")
//                .roles("USER")
//                .authorities("none");
//
//        auth.inMemoryAuthentication()
//                .withUser("admin")
//                .password("admin")
//                .roles("ADMIN")
//                .authorities("admin", "WRITE");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()                            //  定义当需要用户登录时候，转到的登录页面。
                .loginPage("/user/login")           // 设置登录页面
                .loginProcessingUrl("/user/login")       // 自定义的登录接口
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .and()
                .logout()
                .logoutUrl("/user/logout")
                .invalidateHttpSession(true)
                .deleteCookies("SESSION")
                .and()
                .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/user/login", "/user/logout", "/login", "/css/**", "/js/**", "/font-awesome/**", "/skin-config.html").permitAll()     // 设置所有人都可以访问登录页面
                .anyRequest()               // 任何请求,登录后可以访问
                .authenticated()
                .and()
                .csrf().disable()// 关闭csrf防护
                .sessionManagement()
                .maximumSessions(1);
    }
}
